package com.service.Impl;

import com.exception.UserNotFoundException;
import com.mapper.UsersMapper;
import com.pojo.Users;
import com.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class UserServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    @Override
    public Users selectById(Integer userId) {
        if (userId == null || userId <= 0) {
            log.warn("查询用户失败: 非法的用户ID {}", userId);
            throw new IllegalArgumentException("用户ID必须为正整数");
        }

        Users user = usersMapper.selectById(userId);

        if (user == null) {
            log.warn("查询用户失败: 未找到ID为 {} 的用户", userId);
            throw new UserNotFoundException("用户不存在");
        }

        log.info("成功查询用户信息，用户ID: {}, 用户名: {}", userId, user.getUserUsername());
        return user;
    }

    /**
     * 管理用户
     * @param user
     * @return
     */
    @Override
    public Users updateById(Users user) {
        Users u1 = usersMapper.selectByUsername(user.getUserUsername());
        Users u2 = usersMapper.selectById(user.getUserId());

        if(u1 != null && !u2.getUserUsername().equals(user.getUserUsername())) {
            System.out.println("用户名已存在");
        }

        LocalDateTime nowTime = LocalDateTime.now();
        user.setUpdateTime(nowTime);

        usersMapper.updateById(user);
        return user;
    }
}
